from playwright.sync_api import Page
from playwright.sync_api import expect, Page
import os
import time
from utils.tools import get_path


class Page_Object:
    def __init__(self, page: Page):
        self.page = page
        def_timeout = 10000
        self.page.set_default_timeout(def_timeout)
        self.page.set_default_navigation_timeout(def_timeout)

    def navigate(self):
        self.跳转()

    def 跳转(self, path: str = None):
        if path[0] != "/":
            path = f"/{path}"
        self.page.goto(f'{self.page.url.split(".com")[0]}.com{path}')

    from playwright.sync_api import expect, Page
    import os
    import time
    from utils.tools import get_path

    def page_login_save_cookies(self, username: str, password: str):
        """
        通过页面进行登录
        :param username:
        :param password:
        :return:
        """
        if os.path.exists(get_path(f"/.auth/{username}.txt")) and int(time.time() - os.path.getctime(get_path(f"/.auth/{username}.txt"))) < 86400:
            self.page.context.clear_cookies()
            with open(get_path(f"/.auth/{username}.txt")) as f:
                cookies = f.read()
            cookies = eval(cookies)
            self.page.context.add_cookies(cookies)
            self.page.goto("https://0123456789.pingcode.com")
            expect(self.page.locator('.avatar-default').first).to_be_visible()
        else:
            self.page.context.clear_cookies()
            self.page.goto("https://0123456789.pingcode.com")
            self.page.get_by_placeholder("请输入手机号/邮箱").type(username, delay=30)
            self.page.get_by_placeholder("请输入登录密码").fill(password)
            self.page.get_by_role("button", name="登录")
            self.page.get_by_role("button", name="登录").click()
            expect(self.page.locator('.avatar-default').first).to_be_visible()
            cookies = self.page.context.cookies()
            with open(get_path(f"/.auth/{username}.txt"), "w") as f:
                f.write(str(cookies))
